Week 4

Introduction

Today’s exercise exercise will focus on different techniques of clustering and classification. I will use data on housing in areas of Boston and mostly focus on the crime rate in the city. The data can be accessed through the R package MASS. The data contains area-level information on the characteristics of homes (size, value etc.), the demographic composition of the area as well as several variables related to environmental and infrastructural factors. More information on the data is available here and in the original study by Harrison & Rubinfeld (1978).

BTW, I decided to hide my code chunks by default in this course diary as they make reading a bit tedious. You should be able to get the codes by clicking the Code button next to results.

Overview of the dataset

library(MASS)
library(tidyverse)
library(GGally)
library(corrplot)
data(Boston)
dim(Boston)
## [1] 506  14
str(Boston)
## 'data.frame':    506 obs. of  14 variables:
##  $ crim   : num  0.00632 0.02731 0.02729 0.03237 0.06905 ...
##  $ zn     : num  18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
##  $ indus  : num  2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
##  $ chas   : int  0 0 0 0 0 0 0 0 0 0 ...
##  $ nox    : num  0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
##  $ rm     : num  6.58 6.42 7.18 7 7.15 ...
##  $ age    : num  65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
##  $ dis    : num  4.09 4.97 4.97 6.06 6.06 ...
##  $ rad    : int  1 2 2 3 3 3 5 5 5 5 ...
##  $ tax    : num  296 242 242 222 222 222 311 311 311 311 ...
##  $ ptratio: num  15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
##  $ black  : num  397 397 393 395 397 ...
##  $ lstat  : num  4.98 9.14 4.03 2.94 5.33 ...
##  $ medv   : num  24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...
summary(Boston)
##       crim                zn             indus            chas        
##  Min.   : 0.00632   Min.   :  0.00   Min.   : 0.46   Min.   :0.00000  
##  1st Qu.: 0.08205   1st Qu.:  0.00   1st Qu.: 5.19   1st Qu.:0.00000  
##  Median : 0.25651   Median :  0.00   Median : 9.69   Median :0.00000  
##  Mean   : 3.61352   Mean   : 11.36   Mean   :11.14   Mean   :0.06917  
##  3rd Qu.: 3.67708   3rd Qu.: 12.50   3rd Qu.:18.10   3rd Qu.:0.00000  
##  Max.   :88.97620   Max.   :100.00   Max.   :27.74   Max.   :1.00000  
##       nox               rm             age              dis        
##  Min.   :0.3850   Min.   :3.561   Min.   :  2.90   Min.   : 1.130  
##  1st Qu.:0.4490   1st Qu.:5.886   1st Qu.: 45.02   1st Qu.: 2.100  
##  Median :0.5380   Median :6.208   Median : 77.50   Median : 3.207  
##  Mean   :0.5547   Mean   :6.285   Mean   : 68.57   Mean   : 3.795  
##  3rd Qu.:0.6240   3rd Qu.:6.623   3rd Qu.: 94.08   3rd Qu.: 5.188  
##  Max.   :0.8710   Max.   :8.780   Max.   :100.00   Max.   :12.127  
##       rad              tax           ptratio          black       
##  Min.   : 1.000   Min.   :187.0   Min.   :12.60   Min.   :  0.32  
##  1st Qu.: 4.000   1st Qu.:279.0   1st Qu.:17.40   1st Qu.:375.38  
##  Median : 5.000   Median :330.0   Median :19.05   Median :391.44  
##  Mean   : 9.549   Mean   :408.2   Mean   :18.46   Mean   :356.67  
##  3rd Qu.:24.000   3rd Qu.:666.0   3rd Qu.:20.20   3rd Qu.:396.23  
##  Max.   :24.000   Max.   :711.0   Max.   :22.00   Max.   :396.90  
##      lstat            medv      
##  Min.   : 1.73   Min.   : 5.00  
##  1st Qu.: 6.95   1st Qu.:17.02  
##  Median :11.36   Median :21.20  
##  Mean   :12.65   Mean   :22.53  
##  3rd Qu.:16.95   3rd Qu.:25.00  
##  Max.   :37.97   Max.   :50.00
hist(Boston$crim)

The data includes 14 variables from some 500 regions in Boston. All of them are numeric.My main varibale of interest, crime rate, seems highly skewed, with most of the areas having low rates of crime and a few expressing higher rates.

p.values.mat <-cor.mtest(Boston,
                         conf.level = .95)
cor.mat <- cor(Boston)
corrplot.mixed(cor.mat,
         lower.col='black',
               upper='color',
               tl.col='black',
               tl.cex=0.5,
               number.cex=0.5,
               p.mat=p.values.mat$p,
               sig.level=0.05)
Correlation plot

Correlation plot

For a graphical overview of data, I am using the correlation plot to make the plot to some extent readable (compared to pairs or ggpairs). In the plot, I have crossed out all the correlations not significant at 95% confidence level. It seems that the variable chas is not significantly correlated with most of the variables (probably as it is binary). Anyhow, the variable indicates whether the area is bounded by river Charles, which makes little sense to me.

Most of the other variables are statistically correlated, and there seems to be relatively strong correlations, for instance property tax rate (tax) and access to highways (rad) have a correlation of 0.91, age (age) of houses and distance from city centre (dis) have a correlation of -0.75, and nitrous ocygen emissions and proportion of non-retail businesses (=industry) have a correlation of 0.76. These are rather intuitive. Most of the correlations seem moderate, between 0.3 and 0.6.The highest correlations between crime rate occur for variables access to radial highways and property tax rate.

Linear Discriminant analysis

As a next part of the assignment, I am running a Linear Discriminant Analysis (LDA). LDA allows for classifying observations to pre-known categories, based on linear associations between variables in the data.There are two assumptions in the model, the variables are normally distributed and has the same variance. Thus, the process starts by scaling the data.The effects of scaling can be seen on the following summary: all the variables are centered around their mean, which is now 0.

#Scale boston data

boston_scaled <- as.data.frame(scale(Boston))
summary(boston_scaled)
##       crim                 zn               indus              chas        
##  Min.   :-0.419367   Min.   :-0.48724   Min.   :-1.5563   Min.   :-0.2723  
##  1st Qu.:-0.410563   1st Qu.:-0.48724   1st Qu.:-0.8668   1st Qu.:-0.2723  
##  Median :-0.390280   Median :-0.48724   Median :-0.2109   Median :-0.2723  
##  Mean   : 0.000000   Mean   : 0.00000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.007389   3rd Qu.: 0.04872   3rd Qu.: 1.0150   3rd Qu.:-0.2723  
##  Max.   : 9.924110   Max.   : 3.80047   Max.   : 2.4202   Max.   : 3.6648  
##       nox                rm               age               dis         
##  Min.   :-1.4644   Min.   :-3.8764   Min.   :-2.3331   Min.   :-1.2658  
##  1st Qu.:-0.9121   1st Qu.:-0.5681   1st Qu.:-0.8366   1st Qu.:-0.8049  
##  Median :-0.1441   Median :-0.1084   Median : 0.3171   Median :-0.2790  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.5981   3rd Qu.: 0.4823   3rd Qu.: 0.9059   3rd Qu.: 0.6617  
##  Max.   : 2.7296   Max.   : 3.5515   Max.   : 1.1164   Max.   : 3.9566  
##       rad               tax             ptratio            black        
##  Min.   :-0.9819   Min.   :-1.3127   Min.   :-2.7047   Min.   :-3.9033  
##  1st Qu.:-0.6373   1st Qu.:-0.7668   1st Qu.:-0.4876   1st Qu.: 0.2049  
##  Median :-0.5225   Median :-0.4642   Median : 0.2746   Median : 0.3808  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 1.6596   3rd Qu.: 1.5294   3rd Qu.: 0.8058   3rd Qu.: 0.4332  
##  Max.   : 1.6596   Max.   : 1.7964   Max.   : 1.6372   Max.   : 0.4406  
##      lstat              medv        
##  Min.   :-1.5296   Min.   :-1.9063  
##  1st Qu.:-0.7986   1st Qu.:-0.5989  
##  Median :-0.1811   Median :-0.1449  
##  Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.6024   3rd Qu.: 0.2683  
##  Max.   : 3.5453   Max.   : 2.9865

Next, I will first calculate target classes for the LDA model. I am using the crime rate in the areas and dividing it into quartiles. Then, I divide the data into train and test sets by randomly sampling 80% of the areas (train). The rest of the areas are included in the test set.Lastly, I fit the LDA model on the training data and test the model by conducting predictions with the test set

#Save categories of crime rate
bins <- quantile(boston_scaled$crim)
#Create new crime variable
crime <- cut(boston_scaled$crim,
             breaks=bins,
             include.lowest=T,
             label=c(
               "low",
               "med_low",
               "med_high",
               "high"))
boston_scaled$crim <- NULL
boston_scaled$crime <- crime

#Divide data into test and training sets
n <- nrow(boston_scaled)

#Randomly sample 80% of the original rows
#These are used for training
ind <- sample(n, size=n*0.8)

#Train set
train <- boston_scaled[ind,]
#Test set
test <- boston_scaled[-ind,]

#Correct classes in the test set
correct <- test$crime

#Drop crime from test
test <- dplyr::select(test, -crime)

#LDA model
lda.fit <- 
  lda(crime~., data=train)

# the function for lda biplot arrows
#(Stolen from Datacamp)
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "red", tex = 0.75, choices = c(1,2)){
  heads <- coef(x)
  arrows(x0 = 0, y0 = 0, 
         x1 = myscale * heads[,choices[1]], 
         y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
  text(myscale * heads[,choices], labels = row.names(heads), 
       cex = tex, col=color, pos=3)
}

# target classes as numeric
classes <- as.numeric(train$crime)

# predict classes with test data
lda.pred <- predict(lda.fit,
                    newdata = test)

Let’s have a look at the results.

# plot the lda results
plot(lda.fit, dimen = 2,
     col=classes,
     pch=classes)
lda.arrows(lda.fit, myscale = 2)

#summary of the model
lda.fit
## Call:
## lda(crime ~ ., data = train)
## 
## Prior probabilities of groups:
##       low   med_low  med_high      high 
## 0.2623762 0.2351485 0.2549505 0.2475248 
## 
## Group means:
##                  zn      indus        chas        nox         rm        age
## low       0.9940435 -0.9058593 -0.12375925 -0.8848690  0.4066166 -0.9336949
## med_low  -0.1212048 -0.2774201 -0.02367011 -0.5508559 -0.1389731 -0.3058610
## med_high -0.3773415  0.1643633  0.10991367  0.3686017  0.0224771  0.3700800
## high     -0.4872402  1.0171519 -0.03610305  1.0720351 -0.4635588  0.8311561
##                 dis        rad        tax     ptratio      black       lstat
## low       0.9032850 -0.6882537 -0.7286418 -0.49845065  0.3750736 -0.74466322
## med_low   0.3697372 -0.5442448 -0.4755179  0.03366711  0.3554805 -0.13446476
## med_high -0.3354462 -0.4221329 -0.3167420 -0.22476388  0.1064134  0.03879449
## high     -0.8691570  1.6377820  1.5138081  0.78037363 -0.8901512  0.93618249
##                medv
## low       0.5272604
## med_low   0.0045591
## med_high  0.1128689
## high     -0.7102025
## 
## Coefficients of linear discriminants:
##                  LD1           LD2          LD3
## zn       0.182270586  0.7979106628 -0.904467987
## indus   -0.060470552 -0.1963362060  0.292297312
## chas    -0.005582401  0.0135462199  0.112735109
## nox      0.457189696 -0.6738283206 -1.400675765
## rm       0.023973158 -0.0698027106 -0.128343291
## age      0.276848494 -0.3713227787 -0.003276884
## dis     -0.139602247 -0.3327638885  0.323917998
## rad      3.068199288  1.0896143626 -0.001208730
## tax      0.054263045 -0.1950561946  0.570889726
## ptratio  0.178630494 -0.0392931271 -0.140908671
## black   -0.144020238 -0.0009138888  0.169074168
## lstat    0.165635367 -0.2314381116  0.360724123
## medv     0.056470967 -0.4092119322 -0.089237640
## 
## Proportion of trace:
##    LD1    LD2    LD3 
## 0.9493 0.0390 0.0116
# cross tabulate 
#the correct classes vs. predictions
table(correct = correct, 
      predicted = lda.pred$class)
##           predicted
## correct    low med_low med_high high
##   low        9      10        2    0
##   med_low    8      13       10    0
##   med_high   0       3       19    1
##   high       0       0        0   27
table(correct = correct, 
      predicted = lda.pred$class) %>%
  prop.table(2) %>% round(digits=2)
##           predicted
## correct     low med_low med_high high
##   low      0.53    0.38     0.06 0.00
##   med_low  0.47    0.50     0.32 0.00
##   med_high 0.00    0.12     0.61 0.04
##   high     0.00    0.00     0.00 0.96

The most relevant information is included in the scatterplot, aka biplot, of the first two linear discriminants. The plot shows that the grouping with these LDAs of high crime rate areas was relatively successful, whereas the other groups tend to have more overlap. The arrows in the plot show the importance of each variable, and to which direction the are working. It seems that the access to radiaal highways sparates relatively well the high crime rate group. The summary of the model shows the same: mean of rad is high in the high crime rate group, and lower in others.The rad variable has also a large coefficient from the LD1. These findings indicate that crime occurs in places where there are easy to access highways, or, rather, in places where people come and go (probably city centres and some sort of knots in the public transportation system).

K-means clustering

#Reload boston
data(Boston)
boston_scaled <-
  as.data.frame(scale(Boston))

#Calculate distances between observations
#I use Euclidean for no specific reason
#except that the km algorithm uses it
#by default

distances <- dist(boston_scaled)
summary(distances)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##  0.1343  3.4625  4.8241  4.9111  6.1863 14.3970
#Identify correct number of clusters
#Use the WCSS for this purpose

k_max <- 15 #Arbitrary number

twcss <-
  sapply(1:k_max,
         function(k){
           kmeans(
             boston_scaled,k)$tot.withinss})
plot(x=1:k_max,y=twcss,type='l')

#2 seems appropriate
#Run k-means algorithm

km <- kmeans(boston_scaled,centers=2)

#Plot the data set in three parts
pairs(boston_scaled[
  c(1,5,6,7,8,12,13,14)], 
        col=km$cluster)

K-means + LDA

km2 <- kmeans(boston_scaled,centers=3)
boston_scaled$km_clust <- km2$cluster

#LDA model (rename to avoid confusion
#in the next step)
lda.fit2 <- 
  lda(km_clust~., data=boston_scaled)

lda.fit2
## Call:
## lda(km_clust ~ ., data = boston_scaled)
## 
## Prior probabilities of groups:
##         1         2         3 
## 0.3992095 0.2806324 0.3201581 
## 
## Group means:
##         crim         zn        indus        chas         nox         rm
## 1 -0.3549295 -0.4039269  0.009294842  0.11748284  0.01531993 -0.2547135
## 2  0.9693718 -0.4872402  1.074440092 -0.02279455  1.04197430 -0.4146077
## 3 -0.4071299  0.9307491 -0.953383032 -0.12651054 -0.93243813  0.6810272
##          age        dis        rad        tax     ptratio      black
## 1  0.3096462 -0.2267757 -0.5759279 -0.4964651 -0.09219308  0.2473725
## 2  0.7666895 -0.8346743  1.5010821  1.4852884  0.73584205 -0.7605477
## 3 -1.0581385  1.0143978 -0.5976310 -0.6828704 -0.53004055  0.3582008
##         lstat       medv
## 1  0.09168925 -0.1052456
## 2  0.85963373 -0.6874933
## 3 -0.86783467  0.7338497
## 
## Coefficients of linear discriminants:
##                 LD1         LD2
## crim    -0.03654114  0.20373943
## zn       0.08346821  0.34784463
## indus    0.32262409 -0.12105014
## chas     0.04761479 -0.13327215
## nox      0.13026254  0.15610984
## rm      -0.13267423  0.44058946
## age      0.11936644 -0.84880847
## dis     -0.23454618  0.58819732
## rad      1.96894437  0.57933028
## tax      1.10861600  0.53984421
## ptratio  0.13087741 -0.02004405
## black   -0.15432491 -0.06106305
## lstat    0.14002173  0.14786473
## medv    -0.02559139  0.37307811
## 
## Proportion of trace:
##    LD1    LD2 
## 0.8999 0.1001
classes <- 
  as.numeric(boston_scaled$km_clust)

# plot the lda results
plot(lda.fit2, dimen = 2,
     col=classes,
     pch=classes)
lda.arrows(lda.fit2, myscale = 2)

model_predictors <- 
  dplyr::select(train, -crime)

# check the dimensions
dim(model_predictors)
## [1] 404  13
dim(lda.fit$scaling)
## [1] 13  3
# matrix multiplication
matrix_product <- 
  as.matrix(model_predictors) %*% lda.fit$scaling

matrix_product <- as.data.frame(matrix_product)

library(plotly)

plot_ly(x = matrix_product$LD1,
        y = matrix_product$LD2,
        z = matrix_product$LD3,
        type= 'scatter3d',
        mode='markers',
        color=train$crime)
#let's fit still another k-means
#For some reason, the code does not work
#with the original train data
#However, this just loads the boston
#and limirts the same areas so no 
#errors here, I guess

data(Boston)
boston_scaled <- as.data.frame(scale(Boston))
train <- boston_scaled[ind,]
km3 <- kmeans(train, centers=2)

plot_ly(x = matrix_product$LD1,
        y = matrix_product$LD2,
        z = matrix_product$LD3,
        type= 'scatter3d',
        mode='markers',
        color=km3$cluster)

References

Harrison, D. & Rubinfeld, D.L. Hedonic housing prices and the demand for clean air. 1978. Journal of Environmental Economics and Management 5(1), 81-102.